package com.smartwebx.ha.web.util.json.module;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang3.time.DateUtils;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.common.collect.Lists;
import com.smartwebx.ha.dal.usebean.DateValue;

/**
 * Date 类型格式化
 * 
 * @author yyf
 * 
 */
public class DateModule extends SimpleModule {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	Object format = "yyyy-MM-dd";

	public DateModule(Object format) {
		this();
		this.format = format;
	}

	public DateModule() {
		this("DateModule", Version.unknownVersion());
	}

	public DateModule(String name, Version version) {
		super(name, version);
	}

	@Override
	public void setupModule(SetupContext context) {
		super.addSerializer(Date.class, new DateSerializer(format));
		super.setupModule(context);
	}

	public static void main(String[] args) throws JsonGenerationException,
			IOException {
		Date now = new Date();
		Random rand = new Random();
		List<DateValue> dvs = Lists.newArrayList();
		for (int i = 0; i < 10; i++) {
			int t = rand.nextInt(20);
			double d = rand.nextDouble();

			Date tNow = DateUtils.addHours(now, t);
			DateValue v1 = new DateValue();
			v1.setTm(tNow);
			v1.setVal(d);
			dvs.add(v1);
		}
		ObjectMapper mapper = new ObjectMapper();
		mapper.registerModule(new DateModule("yyyy-MM HH:mm:ss"));
		mapper.registerModule(new DoubleModule(2));
		String s = mapper.writeValueAsString(dvs);
		System.out.println(s);
	}

}
